package com.example.demo.service;

import com.example.demo.config.ExcelPathConfig;
import com.example.demo.converter.Excel.ProductConverter;
import com.example.demo.pojo.Product;
import com.example.demo.util.ExcelUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class ProductService {
    @Autowired
    private ExcelPathConfig excelPathConfig;

    public List load() {
        Workbook workbook = ExcelUtil.readExcel(excelPathConfig.getProductFilePath());
        List<List> strings = ExcelUtil.read(workbook);
        List<Product> products = ProductConverter.converterToProduct(strings);
        return products;
    }

    public void store(List products) {
        List strings = ProductConverter.converterToExcel(products);
        ExcelUtil.write(strings, excelPathConfig.getProductFilePath());
    }

    public void add(Product product) {
        List<Product> products = load();
        products.add(product);
        store(products);
    }

    public Product getOne(Integer id) {
        List<Product> products = load();
        for (Product product : products) {
            if (product.getId() == id) {
                return product;
            }
        }
        return null;
    }

    public void update(Product p) {
        List<Product> products = load();
        for (Product product : products) {
            if (product.getId() == p.getId()) {
                Collections.replaceAll(products, product, p);
            }
        }
        store(products);
    }

    public void deleteOne(Integer id) {
        List<Product> products = load();
        for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            if (product.getId() == id) {
                products.remove(product);
                i--;
            }
        }
        store(products);
    }
}
